package cn.com.sr.plugin.sso.cas;

import com.apexedu.framework.util.DBUtil;
import org.jasig.cas.client.util.AssertionHolder;
import org.jasig.cas.client.validation.Assertion;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by SwordRays on 2015-10-20.
 */
public class CASLoginAdapterFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }
    public void destroy() {
    }
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//        HttpSession session = ((HttpServletRequest) request).getSession();
//        Object loginUser = session.getAttribute("LogonUser");
//        //如果session中没有用户信息，则填充用户信息
//        if (null == loginUser) {
//            //从Cas服务器获取登录账户的用户名
//            Assertion assertion = AssertionHolder.getAssertion();
//            String username = assertion.getPrincipal().getName();
//            try {
//                //根据单点登录的账户的用户名，从数据库用户表查找用户信息， 填充到session中
//                List<User> userList = DBUtil.queryAllBeanList("select * from tuser where userid=?",User.class,username);
//                if(null != userList && userList.size() > 0){
//                    User user = userList.get(0);
//                    session.setAttribute("LogonUser", user);
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        chain.doFilter(request, response);

        HttpSession session = ((HttpServletRequest) request).getSession();
        Object loginUser = session.getAttribute("sso.cas.id");

        //如果session中没有用户信息，则填充用户信息
        if (null == loginUser) {
            //从Cas服务器获取登录账户的用户名
            Assertion assertion = AssertionHolder.getAssertion();
            String username = assertion.getPrincipal().getName();
            try {
                //根据单点登录的账户的用户名，从数据库用户表查找用户信息， 填充到session中
                List<Map<String,String>> userList = DBUtil.queryForList("select * from tuser where userid=?", username);
                if (null != userList && userList.size() > 0) {
                    Map<String,String> user = userList.get(0);
                    session.setAttribute("sso.cas.id", user.get("id"));
                    session.setAttribute("sso.cas.username", user.get("userid"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        chain.doFilter(request, response);
    }
}
